import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'
interface UserState {
  songList: Array<any>
  currentIndex: number
  playerStatus: {
    isPlaying: boolean
    volume: number
    handlePlay: boolean
  }
}

export const useSongStore = defineStore('song', {
  state: (): UserState => ({
    songList: [],
    currentIndex: 0,
    playerStatus: {
      isPlaying: false,
      volume: 40,
      handlePlay: false
    }
  }),
  actions: {
    async setCurrentSong(proxy, musicInfo) {
      const currentSong = { ...musicInfo }
      if (this.playerStatus.handlePlay) {
        this.setPlaying()
      }
      const res = await proxy.requestApi.song_url(musicInfo.id)
      if (res.code !== 200) {
        ElMessage.warning('获取音乐失败')
      }
      currentSong.url = res.data[0].url
      this.songList.unshift(currentSong)
      this.currentIndex = 0
      this.playerStatus.handlePlay = !this.playerStatus.handlePlay
    },
    setPlaying() {
      this.playerStatus.isPlaying = !this.playerStatus.isPlaying
    },
    playSong(audioRef) {
      audioRef.value?.play()
      this.playerStatus.isPlaying = true
    },
    stopSong(audioRef) {
      audioRef.value?.pause()
      this.playerStatus.isPlaying = false
    }
  },
  getters: {
    currentSong(state: UserState) {
      return state.songList[state.currentIndex]
    }
  }
})
